package com.jerry.hm.datastructure.deque;

import java.util.Iterator;

/**
 * 数组实现的双端队列
 *
 * @author Jerry
 * @since 2024/10/4 15:08
 */
public class ArrayDeque<E> implements Deque<E>, Iterable<E> {

    private E[] array;
    private int head;
    private int tail;

    public ArrayDeque(int capacity) {
        array = (E[]) new Object[capacity + 1];
    }

    private int inc(int index) {
        return index + 1 > array.length - 1 ? 0 : index + 1;
    }

    private int dec(int index) {
        return index - 1 < 0 ? array.length - 1 : index - 1;
    }

    /**
     * 头部添加元素
     *
     * @param e
     * @return
     */
    @Override
    public boolean offerFirst(E e) {
        if (isFull()) {
            return false;
        }
        head = dec(head);
        array[head] = e;
        return true;
    }

    /**
     * 尾部添加元素
     *
     * @param e
     * @return
     */
    @Override
    public boolean offerLast(E e) {
        if (isFull()) {
            return false;
        }
        array[tail] = e;
        tail = inc(tail);
        return true;
    }

    /**
     * 头部移除元素
     *
     * @return
     */
    @Override
    public E pollFirst() {
        if (isEmpty()) {
            return null;
        }
        E removed = array[head];
        array[head] = null;
        head = inc(head);
        return removed;
    }

    /***
     * 尾部移除元素
     * @return
     */
    @Override
    public E pollLast() {
        if (isEmpty()) {
            return null;
        }
        tail = dec(tail);
        E e = array[tail];
        array[tail] = null;
        return e;
    }

    /**
     * 获取头部元素
     *
     * @return
     */
    @Override
    public E peekFirst() {
        if (isEmpty()) {
            return null;
        }
        return array[head];
    }

    /**
     * 获取尾部元素
     *
     * @return
     */
    @Override
    public E peekLast() {
        if (isEmpty()) {
            return null;
        }
        return array[dec(tail)];
    }

    /**
     * 是否空
     *
     * @return
     */
    @Override
    public boolean isEmpty() {
        return head == tail;
    }

    /**
     * 是否满
     *
     * @return
     */
    @Override
    public boolean isFull() {
        if (head > tail) {
            return head - tail == 1;
        } else if (head < tail) {
            return tail - head == array.length - 1;
        } else {
            return false;
        }
    }

    @Override
    public Iterator<E> iterator() {

        return new Iterator<>() {

            private int cur = head;

            @Override
            public boolean hasNext() {
                return cur != tail;
            }

            @Override
            public E next() {
                E value = array[cur];
                cur = inc(cur);
                return value;
            }
        };
    }

}
